<?php

namespace App\Services;

use App\Models\Unit;
use App\Models\User;
use App\Models\Person;
use App\Models\BpmUserToDo;
use App\Models\BpmMaindata;
use App\Models\BpmUserReadDoc;
use App\Models\BpmArchivedData;
use Illuminate\Support\Facades\Log;
use App\Models\AssessmentUserAcceptance;

class ProcessService extends BaseService
{
    /**
     * 默认展示数目
     */
    const DEFAULT_NUMBER = 0;

    /**
     * @var 用户名
     */
    public $username;

    public function __construct()
    {
        $this->getUserName();
    }

    /**
     * 用户登陆用户的用户名
     */
    public function getUserName()
    {
        if (empty(auth('api')->user())) {
            $this->username = '';
        } else {
            $user = auth('api')
                ->user()
                ->toArray();

            $this->username =$user['username'];
        }
    }


    /**
     * 获取到服务列表数据
     * @param array $parameters
     * @return array
     */
    public function getServiceList(array $parameters) : array
    {
        switch ($parameters['type']) {
            case 1:
                return $this->getNeedDealList($parameters);
            case 2:
                return $this->getNeedReadList($parameters);
            case 3:
                return $this->getJoinList($parameters);
            case 4:
                return $this->getFinishList($parameters);
            case 5:
                return $this->getJoinList($parameters);
            default:
                return $this->getFinishList($parameters);
        }
    }

    /**
     * 获取到服务流程数量
     * @return array
     */
    public function getServiceNumber() : array
    {
        return [
            array('name'=>'待办','number'=>$this->getNeedDealNumber()),
            array('name'=>'待阅','number'=>$this->getNeedReadNumber()),
            array('name'=>'参与','number'=>$this->getJoinNumber()),
            array('name'=>'办结','number'=>$this->getFinishNumber()),
            array('name'=>'已阅','number'=>$this->getMyProcessNumber()),
            array('name'=>'团队服务单','number'=>$this->getMyGroupProcessNumber()),

        ];
    }

    /**
     * 我的代办
     * @return int
     */
    public function getNeedDealNumber() : int
    {
        try{
            $taskIdArray = AssessmentUserAcceptance::where('add_wait_name',$this->username)
                ->distinct()
                ->where('is_wait',1)
                ->pluck('add_wait_task_id')
                ->toArray();

            return BpmUserToDo::where('Userid',$this->username)
                ->whereNotIn('Taskid',$taskIdArray)
                ->count();
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('服务流程 获取我的代办数量异常：'.$exception->getMessage());

            report($exception);

            return self::DEFAULT_NUMBER;
        }
    }

    /**
     * 我的代办列表
     * @param array $parameters
     * @return array
     */
    public function getNeedDealList(array $parameters) : array
    {
        try{
            $taskIdArray = AssessmentUserAcceptance::where('add_wait_name',$this->username)
                ->distinct()
                ->where('is_wait',1)
                ->pluck('add_wait_task_id')
                ->toArray();

            $data =  BpmUserToDo::filter($parameters)
                ->where('Userid',$this->username)
                ->whereNotIn('Taskid',$taskIdArray)
                ->select([
                    'WF_OrUnid',
                    'Subject',
                    'WF_AddName_CN',
                    'WF_DocCreated',
                    'WF_ProcessName',
                    'NodeName',
                    'Nodeid'
                ])
                ->orderBy('StartTime','Desc')
                ->paginate(30)
                ->map(function ($item){
                    return [
                        'id'        => $item->WF_OrUnid,
                        'subject'   => $item->Subject,
                        'title'     => $item->WF_ProcessName,
                        'date'      => date('Y-m-d',strtotime($item->WF_DocCreated)),
                        'username'  => $item->WF_AddName_CN,
                        'node_name' => $item->NodeName,
                        'node_id'   => $item->Nodeid
                    ];
                })
                ->toArray();
            //return $data;
            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('服务流程 我的代办列表异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 我的待阅
     * @return int
     */
    public function getNeedReadNumber() : int
    {
        try{
            return BpmUserReadDoc::where('Userid',$this->username)
                ->where('readStatus','Current')
                ->count();
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('服务流程 获取我的代阅数量异常：'.$exception->getMessage());

            report($exception);

            return self::DEFAULT_NUMBER;
        }
    }

    /**
     * 我的待阅列表数据
     * @param array $parameters
     * @return array
     */
    public function getNeedReadList(array $parameters) : array
    {
        try{
            $data = BpmUserReadDoc::where('Userid',$this->username)
                ->where('readStatus','Current')
                ->select([
                    'WF_OrUnid',
                    'Subject',
                    'WF_AddName_CN',
                    'WF_DocCreated',
                    'WF_ProcessName',
                    'NodeName',
                    'Nodeid'
                ])
                ->orderBy('WF_DocCreated','Desc')
                ->paginate(30)
                ->map(function ($item){
                    return [
                        'id'        => $item->WF_OrUnid,
                        'subject'   => $item->Subject,
                        'title'     => $item->WF_ProcessName,
                        'date'      => date('Y-m-d',strtotime($item->WF_DocCreated)),
                        'username'  => $item->WF_AddName_CN,
                        'node_name' => $item->NodeName,
                        'node_id'   => $item->Nodeid
                    ];
                })
                ->toArray();

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('服务流程 我的待阅列表数据异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 我的参与
     * @return int
     */
    public function getJoinNumber() : int
    {
        try{
            return BpmMaindata::where(function ($query){
                return $query->where('WF_EndUser','like','%,'.$this->username.',%')
                    ->orWhere('WF_EndUser','like','%,'.$this->username)
                    ->orWhere('WF_EndUser','like',$this->username.',%')
                    ->orWhere('WF_EndUser',$this->username);
            })
                ->count();
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('服务流程 获取我的参与数量异常：'.$exception->getMessage());

            report($exception);

            return self::DEFAULT_NUMBER;
        }
    }

    /**
     * 我的参与列表
     * @param array $parameters
     * @return array
     */
    public function getJoinList(array $parameters) : array
    {
        try{
            $data = BpmMaindata::filter($parameters)
                ->where(function ($query){
                    return $query->where('WF_EndUser','like','%,'.$this->username.',%')
                        ->orWhere('WF_EndUser','like','%,'.$this->username)
                        ->orWhere('WF_EndUser','like',$this->username.',%')
                        ->orWhere('WF_EndUser',$this->username);
                })
                ->select([
                    'WF_OrUnid',
                    'Subject',
                    'WF_AddName_CN',
                    'WF_DocCreated',
                    'WF_ProcessName',
                    'WF_CurrentNodeid',
                    'WF_CurrentNodeName'

                ])
                ->orderBy('WF_DocCreated','DESC')
                ->paginate(30)
                ->map(function ($item){
                    return [
                        'id'        => $item->WF_OrUnid,
                        'subject'   => $item->Subject,
                        'title'     => $item->WF_ProcessName,
                        'date'      => date('Y-m-d',strtotime($item->WF_DocCreated)),
                        'username'  => $item->WF_AddName_CN,
                        'node_name' => $item->WF_CurrentNodeName,
                        'node_id'   => $item->WF_CurrentNodeid
                    ];
                })
                ->toArray();

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('服务流程 我的参与列表数据异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 已办结
     * @return int
     */
    public function getFinishNumber() : int
    {
        try{
             return BpmArchivedData::where(function ($query){
                 return $query->where('WF_AddName',$this->username)
                     ->orWhere('WF_EndUser','like','%,'.$this->username.',%')
                     ->orWhere('WF_EndUser','like','%,'.$this->username)
                     ->orWhere('WF_EndUser','like',$this->username.',%')
                     ->orWhere('WF_EndUser',$this->username);
             })
                ->distinct()
                ->pluck('WF_OrUnid')
                ->count();

        }catch (\Exception $exception){
            Log::channel('api')
                ->info('服务流程 获取完结数量异常：'.$exception->getMessage());

            report($exception);

            return self::DEFAULT_NUMBER;
        }
    }

    /**
     * 已办结列表数据
     * @param array $parameters
     * @return array
     */
    public function getFinishList(array $parameters) : array
    {
        try {
            $data = BpmArchivedData::filter($parameters)
                ->where(function ($query){
                    return $query->where('WF_AddName',$this->username)
                        ->orWhere('WF_EndUser','like','%,'.$this->username.',%')
                        ->orWhere('WF_EndUser','like','%,'.$this->username)
                        ->orWhere('WF_EndUser','like',$this->username.',%')
                        ->orWhere('WF_EndUser',$this->username);
                })
                ->select([
                    'WF_OrUnid',
                    'Subject',
                    'WF_AddName_CN',
                    'WF_DocCreated',
                    'WF_ProcessName',
                    'WF_CurrentNodeid',
                    'WF_CurrentNodeName'
                ])
                ->paginate(30)
                ->map(function ($item){
                    return [
                        'id'        => $item->WF_OrUnid,
                        'subject'   => $item->Subject,
                        'title'     => $item->WF_ProcessName,
                        'date'      => date('Y-m-d',strtotime($item->WF_DocCreated)),
                        'username'  => $item->WF_AddName_CN,
                        'node_name' => $item->WF_CurrentNodeName,
                        'node_id'   => $item->WF_CurrentNodeid
                    ];
                })
                ->toArray();

            return customer_return_success('success',$data);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('服务流程 已办结列表数据异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 我的服务单
     * 参与并进行
     * 我的代办
     * @return int
     */
    public function getMyProcessNumber() : int
    {
        try{
            $joinNumber = $this->getJoinNumber();

            $needDealNumber = $this->getNeedDealNumber();

            return $joinNumber + $needDealNumber;
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('服务流程 获取我的服务单数量异常：'.$exception->getMessage());

            report($exception);

            return self::DEFAULT_NUMBER;
        }
    }

    /**
     * 我的服务单列表
     * @return array
     */
    public function getMyProcessList(array $parameters) : array
    {
        try{
            return customer_return_success('success',[]);

        }catch (\Exception $exception){
            Log::channel('api')
                ->info('服务流程 已办结列表数据异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }

    /**
     * 我的团队服务单
     * @return int
     */
    public function getMyGroupProcessNumber() : int
    {
        try{


            $isLeader = Unit::where('unit.parent_id', 375)
                ->where('unit.is_deleted', 0)
                ->leftJoin('pms.person as p', 'p.unit_id', '=', 'unit.id')
                ->leftJoin('pms.r_person_post as rpp', 'p.id', '=', 'rpp.person_id')
                ->leftJoin('pms.user as us', 'us.person_id', '=', 'p.id')
                ->where('rpp.post_id', '!=', 9)
                ->where('p.is_deleted', 0)
                ->where('us.username', auth('api')->user()->username ?? '')
                ->exists();

            if(!$isLeader){
                return 0;
            }
            //获取我的团队下的所有用户的username
            $person = auth('api')->user()->person;

            if (!is_null($person)){
                $unitId = $person->unit_id;

                if (!empty($unitId)) {
                    $personIdArray = Person::where('unit_id',$unitId)
                        ->pluck('id')
                        ->toArray();

                    $usernames = User::whereIn('person_id',$personIdArray)
                        ->pluck('username')
                        ->toArray();
                }
            }

            if (!isset($usernames) || empty($usernames)) {
                $usernames = [$this->username];
            }

            $taskIdArray = AssessmentUserAcceptance::whereIn('add_wait_name',$usernames)
                ->distinct()
                ->where('is_wait',1)
                ->pluck('add_wait_task_id')
                ->toArray();

            $needDealNumber =  BpmUserToDo::whereIn('Userid',$usernames)
                ->whereNotIn('Taskid',$taskIdArray)
                ->selectRaw('count(DISTINCT `WF_OrUnid`, `Subject`, `WF_AddName_CN`, `WF_DocCreated`, `WF_ProcessName`, `NodeName`, `Nodeid`) as count')
                ->get()
                ->first();
            return $needDealNumber->count??0;

            /*
            $total = 0;

            foreach ($usernames as $username) {
//                $joinNumber = BpmMaindata::where('WF_EndUser','like','%,'.$username.',%')
//                    ->orWhere('WF_EndUser','like','%,'.$username)
//                    ->orWhere('WF_EndUser','like',$username.',%')
//                    ->orWhere('WF_EndUser',$username)
//                    ->count();

                $taskIdArray = AssessmentUserAcceptance::where('add_wait_name',$username)
                    ->distinct()
                    ->where('is_wait',1)
                    ->pluck('add_wait_task_id')
                    ->toArray();

                $needDealNumber =  BpmUserToDo::where('Userid',$username)
                    ->whereNotIn('Taskid',$taskIdArray)
                    ->count();

//                $total += $joinNumber + $needDealNumber;
                $total += $needDealNumber;
            }

            return $total;*/
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('服务流程 获取我的团队服务单数量异常：'.$exception->getMessage());

            report($exception);

            return self::DEFAULT_NUMBER;
        }
    }

    /**
     * 我的团队服务单列表
     * @return array
     */
    public function getMyGroupProcessList($parameters) : array
    {
        try{
            return customer_return_success('success',[]);
        }catch (\Exception $exception){
            Log::channel('api')
                ->info('服务流程 我的团队服务单列表数据异常：'.$exception->getMessage());

            report($exception);

            return customer_return_error('数据异常，请稍后再试');
        }
    }
}
